// pages/student/home/home.js
import { courses, courseCategories } from '../../../utils/mockData.js'

Page({
  data: {
    categories: courseCategories,
    bannerCourses: [],
    hotCourses: [],
    liveCourses: [],
    recommendCourses: [],
    userInfo: null,
    currentBanner: 0
  },
  onLoad() {
    this.loadUserInfo()
    this.loadData()
    this.startBannerAutoPlay()
  },
  onUnload() {
    if (this.bannerTimer) {
      clearInterval(this.bannerTimer)
    }
  },
  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo')
    this.setData({ userInfo })
  },
  loadData() {
    // 模拟加载数据
    this.setData({
      bannerCourses: courses.slice(0, 3),
      hotCourses: courses.slice(0, 4),
      liveCourses: courses.filter(c => c.is_live),
      recommendCourses: courses.slice(0, 6)
    })
  },
  startBannerAutoPlay() {
    this.bannerTimer = setInterval(() => {
      const { currentBanner, bannerCourses } = this.data
      const nextBanner = (currentBanner + 1) % bannerCourses.length
      this.setData({ currentBanner: nextBanner })
    }, 3000)
  },
  onBannerChange(e) {
    this.setData({ currentBanner: e.detail.current })
  },
  goToCategory(e) {
    const categoryId = e.currentTarget.dataset.id
    wx.switchTab({
      url: '/pages/student/course-square/course-square'
    })
  },
  goToCourseSquare() {
    wx.switchTab({
      url: '/pages/student/course-square/course-square'
    })
  },
  goToCourseDetail(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/student/course-detail/course-detail?id=${id}`
    })
  },
  goToLiveRoom(e) {
    const id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/student/live-room/live-room?courseId=${id}`
    })
  },
  goToMall() {
    wx.navigateTo({
      url: '/pages/student/mall/mall'
    })
  },
  onPullDownRefresh() {
    this.loadData()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  }
})
